<?php

namespace App\Dao;

use App\Model\UsersUpgradeModel;
use App\Services\Logger;
use App\Services\SmsServices;
use App\Services\WechatServices;
use Illuminate\Support\Facades\DB;

class CommonDao extends BaseDao
{

    public static $user_sys_id = 10000;
    //实时单价总资金池/金币总数量
    public static function real_time_price()
    {
        //总池
        $sys_balance = SettingsDao::get_set_value('sys_balance');
        if($sys_balance == 0){
            return  0.05;
        }
        //获取用户金币和
        $sys_score_all = SettingsDao::get_set_value('sys_score_all');
        if($sys_score_all == 0){
            return 0.05;
        }
        $item_money = bcdiv($sys_balance,$sys_score_all,2);
        if($item_money == 0){
            return 0.05;
        }
        return $item_money;
    }


    public static function mixGoodsPrice($mix_goods_price = 0)
    {
        SettingsDao::builder_query([
            'key_name'=>'sys_balance'
        ])->increment('key_text',$mix_goods_price);
    }


    public static function mixScorePrice($mix_goods_price = 0)
    {
        SettingsDao::builder_query([
            'key_name'=>'sys_score_all'
        ])->increment('key_text',$mix_goods_price);
    }

    public static function mixScoreShengPrice($mix_goods_price = 0)
    {
        SettingsDao::builder_query([
            'key_name'=>'sys_score_sheng'
        ])->increment('key_text',$mix_goods_price);
    }


    //静态每天释放
    public static function user_send_score()
    {

        $date = strtotime(date('Y-m-d'));
        $query = OrdersDao::builder_query()
            ->where('recive_time','<',$date)
            ->where('is_send_status',0)
            ->where('status',1)
            ->where('order_send_score_recive','>',0);
        if(!$query->exists()){
            self::error('订单不存在');
        }
        $info = $query->first()->toArray();
        $now_price = CommonDao::real_time_price();
        //判断已经释放的大就停止
        $every_day_score = bcdiv($info['order_send_score_jingtai'],$info['days'],10);
        $every_day_price = bcmul($now_price,$every_day_score,2);


        $status = 0;
        //获取仙子啊订单还能分的总权益
        if($info['order_send_max_recive'] < $every_day_price){
            $every_day_price = $info['order_send_max_recive'];
            $every_day_score = bcdiv($every_day_price,$now_price,10);
            $status = 1;
        }
        $userInfo = UsersDao::builder_user_query([
            'user_id'=>$info['user_id']
        ])->first()->toArray();
        //个人最大收益总和
        if($userInfo['max_recive'] < $every_day_price){
            $every_day_price = $userInfo['max_recive'];
            $every_day_score = bcdiv($every_day_price,$now_price,10);
            $status = 1;
        }



        if($info['order_send_max_recive'] == 0){
            $status = 1;
        }
        //停止发放
        if($info['order_send_score_recive'] == 0){
            $status = 1;
        }
        DB::beginTransaction();
        try {
            //进行发放金币并且减少对应值
            if($every_day_price > 0){
                //减少可用额度
                $query->decrement('order_send_max_recive',$every_day_price);
                //减少赠送金币
                $query->decrement('order_send_score_recive',$every_day_score);
                //减少用户最大收益
                UsersDao::builder_user_query([
                    'user_id'=>$info['user_id']
                ])->decrement('max_recive',$every_day_price);
                //发放金币
                BillsScoreDao::moneyUpdate($info['user_id'],$every_day_score,'消费获取绿色消费金币');
            }
            //修改订单状态
            OrdersDao::builder_query(['order_id'=>$info['order_id']])->update([
                'is_send_status'=>$status,
                'recive_time'=>$date
            ]);
            DB::commit();
        }catch (\Exception $exception){
            DB::rollBack();
            Logger::jingtai('====>'.$exception->getMessage());
            self::error($exception->getMessage());
        }

    }



    //静态金币查询剩余的到剩余金币池子
    public static function ShengYuScoreJingTai()
    {
        //查询订单为1
        $query = OrdersDao::builder_query()
            ->where('is_send_status',1)->where('status',1);
        if(!$query->exists()){
            self::error('订单不存在');
        }
        $info = $query->first()->toArray();
        if($info['order_send_score_recive'] ==0){
            $query->update([
                'is_send_status'=>2,
            ]);
            return;
        }
        //判断剩余的静态金币直接移到池子里面还是
        //自动回流
        if(SettingsDao::get_set_value('is_open_sys') == 1){
            //====>根据剩余金币算出来当前价值放到资金池
            $order_send_score_recive = $info['order_send_score_recive'];
            //根据单价算出来金额
            $rang_li_price = bcmul($order_send_score_recive,CommonDao::real_time_price(),2);
            //放到资金池后再根据单价算出来金币放到资金池
            DB::beginTransaction();
            try {
                //增加资金池金额
                self::mixGoodsPrice($rang_li_price);
                //计算金币额度并且一次行沉淀到系统账号
                $scorex = bcdiv($rang_li_price,self::real_time_price(),10);
                BillsScoreDao::moneyUpdate(self::$user_sys_id,$scorex,'系统沉淀账号');
                self::mixScorePrice($scorex);
                $query->update([
                    'order_send_score_recive'=>0,
                    'is_send_status'=>2,
                ]);
                DB::commit();
            }catch (\Exception $exception){
                DB::rollBack();
                self::error($exception->getMessage());
            }
        }else{
            //不回流
            DB::beginTransaction();
            try {
                //放到金币的地方
                self::mixScoreShengPrice($info['order_send_score_recive']);
                $query->update([
                    'order_send_score_recive'=>0,
                    'is_send_status'=>2,
                ]);
                DB::commit();
            }catch (\Exception $exception){
                DB::rollBack();
                self::error($exception->getMessage());
            }
        }

    }

    public static function send_sms(array $params)
    {
        checkForData(
            ['phone'],
            ['请输入手机号'],
            $params
        );
        SmsServices::send($params);
    }


    //动态收益
    public static function dongtai()
    {
        $query = OrdersDao::builder_query()
            ->where('order_send_score_dongtai_recive',0)
            ->where('status',1);
        if(!$query->exists()){
            self::error('订单不存在');
        }
        $info = $query->first()->toArray();
        //根据
        $order_send_score_dongtai = $info['order_send_score_dongtai'];
        $order_send_score_dongtai_price = bcmul($order_send_score_dongtai,CommonDao::real_time_price(),2);
        if(!($order_send_score_dongtai_price > 0)){
            $query->update([
                'order_send_score_dongtai_recive'=>99999999999
            ]);
        }
        //30给上级
        $userInfo = UsersDao::builder_user_query([
            'user_id'=>$info['user_id']
        ])->first()->toArray();
        $moneyBalance = 0;
        $start_time = time();
        Logger::dongtai('=====>'.$start_time);

        //直推30%
        DB::beginTransaction();
        try {
            if($userInfo['spread_id'] != 0){
                $spreadInfo = UsersDao::builder_user_query([
                    'user_id'=>$userInfo['spread_id']
                ])->first()->toArray();
                $percent_30 = bcmul($order_send_score_dongtai,0.3,10);
                $percent_30_price = bcmul($percent_30,CommonDao::real_time_price(),2);


                //判断用户的声誉金额
                if($spreadInfo['max_recive'] < $percent_30_price){
                    $percent_30_price = $spreadInfo['max_recive'];
                    $percent_30 = bcdiv($percent_30_price,CommonDao::real_time_price(),2);
                }

                $moneyBalance = bcadd($moneyBalance,$percent_30_price,2);
                //发放金币到个人
                if($percent_30_price > 0 && $spreadInfo['vip_index_level'] == 1){

                    BillsScoreDao::moneyUpdate($spreadInfo['user_id'],$percent_30,'动态释放(直推)');

                    UsersDao::builder_user_query([
                        'user_id'=>$spreadInfo['user_id']
                    ])->decrement('max_recive',$percent_30_price);

                    sleep(1);
                }



                if($spreadInfo['spread_id'] != 0){
                    $spreadInfo = UsersDao::builder_user_query([
                        'user_id'=>$spreadInfo['spread_id']
                    ])->first()->toArray();
                    $percent_10 = bcmul($order_send_score_dongtai,0.1,10);
                    $percent_10_price = bcmul($percent_10,CommonDao::real_time_price(),2);
                    if($spreadInfo['max_recive'] < $percent_10_price){
                        $percent_10_price = $spreadInfo['max_recive'];
                        $percent_10 = bcdiv($percent_10_price,CommonDao::real_time_price(),2);
                    }
                    $moneyBalance = bcadd($moneyBalance,$percent_10_price,2);

                    if($percent_10_price > 0  && $spreadInfo['vip_index_level'] == 1){
                        BillsScoreDao::moneyUpdate($spreadInfo['user_id'],$percent_10,'动态释放(间推)');

                        UsersDao::builder_user_query([
                            'user_id'=>$spreadInfo['user_id']
                        ])->decrement('max_recive',$percent_10_price);
                        sleep(1);

                    }
                }
            }




            $uu_info = UsersDao::builder_user_query([
                'user_id'=>$info['user_id']
            ])->first()->toArray();
            $spread_id = $uu_info['spread_id'];

            $lilv = [0,0.15,0.25,0.35,0.45,0.55,0.6];
            $index_level = 0;
            $index_score = 0;
            $index_add_scores  = 0;
            $index_uid = 0;
            //无限循环进行极差返费
            while (true){
                if($spread_id == 0 ){
                    break;
                }

                //判断用户信息
                $u_spread_info = UsersDao::builder_user_query([
                    'user_id'=>$spread_id
                ])->first()->toArray();
                //平级奖励
                if($u_spread_info['vip_level'] == 0){
                    $spread_id = $u_spread_info['spread_id'];
                    continue;
                }
                //评级释放
                if($u_spread_info['vip_level'] == $index_level){
                    //减去上一个人的部分金币10%
                    $item_scorexx = bcmul($index_score,0.1,10);
                    $balance_noww = bcmul($item_scorexx,self::real_time_price(),2);
                    if($u_spread_info['max_recive'] < $balance_noww){
                        $balance_noww = $u_spread_info['max_recive'];
                        $item_scorexx = bcdiv($balance_noww,self::real_time_price(),10);
                    }


                    if($item_scorexx > 0){
                        BillsScoreDao::moneyUpdate($u_spread_info['user_id'],$item_scorexx,$info['user_id'].'账号感恩奖励');
                        BillsScoreDao::moneyUpdate($index_uid,-($item_scorexx),'贡献奖奖励');
                        UsersDao::builder_user_query([
                            'user_id'=>$u_spread_info['user_id']
                        ])->decrement('max_recive',$item_scorexx);
                        $index_score = $item_scorexx;
                        $index_uid = $u_spread_info['user_id'];
                    }
                    $spread_id = $u_spread_info['spread_id'];
                    continue;
                }

                //大于
                if($u_spread_info['vip_level'] > $index_level){
                    //计算单个人的比例
                    $item_scorex = bcsub(bcmul($order_send_score_dongtai,$lilv[$u_spread_info['vip_level']],10),$index_add_scores,10);
                    $balance_now = bcmul($item_scorex,self::real_time_price(),2);


                    if($u_spread_info['max_recive'] < $balance_now){
                        $balance_now = $u_spread_info['max_recive'];
                        $item_scorex = bcdiv($balance_now,self::real_time_price(),10);
                    }

                    if($item_scorex > 0){
                        BillsScoreDao::moneyUpdate($u_spread_info['user_id'],$item_scorex,$info['user_id'].'账号消费团队奖励');
                        UsersDao::builder_user_query([
                            'user_id'=>$u_spread_info['user_id']
                        ])->decrement('max_recive',$item_scorex);
                        $index_level = $u_spread_info['vip_level'];
                        $index_score = $item_scorex;
                        $index_add_scores = bcadd($index_add_scores,$item_scorex,10);
                        $index_uid = $u_spread_info['user_id'];
                        $moneyBalance = bcadd($moneyBalance,$balance_now,2);
                    }

                    //奖励给人金币
                }
                $spread_id = $u_spread_info['spread_id'];

                sleep(1);

            }
            Logger::dongtai('=====>' . (($start_time) - time()));

            $order_send_score_dongtai_sheng = $order_send_score_dongtai_price - $moneyBalance;
            //剩下的钱回流
            if(SettingsDao::get_set_value('is_open_sys') == 1){
                //====>根据剩余金币算出来当前价值放到资金池
                //根据单价算出来金额
                $rang_li_price = $order_send_score_dongtai_sheng;
                //放到资金池后再根据单价算出来金币放到资金池
                self::mixGoodsPrice($rang_li_price);
                //计算金币额度并且一次行沉淀到系统账号
                $scorex = bcdiv($rang_li_price,self::real_time_price(),10);
                BillsScoreDao::moneyUpdate(self::$user_sys_id,$scorex,'系统沉淀账号');
                self::mixScorePrice($scorex);
                $query->update([
                    'order_send_score_dongtai_recive'=>$info['order_send_score_dongtai'],
                ]);
            }else{
                //不回流
                self::mixScoreShengPrice(bcdiv($order_send_score_dongtai_sheng,CommonDao::real_time_price(),10));
                $query->update([
                    'order_send_score_dongtai_recive'=>$info['order_send_score_dongtai'],
                ]);
            }
            DB::commit();
        }catch ( \Exception $exception){
            DB::commit();
            self::error($exception->getMessage());
        }





    }

    public static function qr_code(array $params)
    {
        return WechatServices::qr_code($params);
    }

    public static function user_urgrade_pageinage(array $all)
    {
        $query = UsersUpgradeModel::query();

        $query->when(checkIsHasField($all,'user_id'),function ($query)use ($all){
            $query->where('user_id',$all['user_id']);
        });

        return $query->orderByDesc('created_at')->paginate();
    }
}
